<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-06-28
 */

namespace weapp\AirBottle\controller;

use think\Page;
use think\Db;
use app\common\controller\Weapp;
use weapp\AirBottle\model\AirBottleModel;
use weapp\AirBottle\model\AirFactoryModel;

/**
 * 插件的控制器
 */
class AirBottle extends Weapp
{
    /**
     * 实例化模型
     */
    private $model;

    /**
     * 实例化对象
     */
    private $db;

    /**
     * 插件基本信息
     */
    private $weappInfo;

    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();
        $this->model = new AirBottleModel;
        $this->db = Db::name('WeappAirBottle');

        /*插件基本信息*/
        $this->weappInfo = $this->getWeappInfo();
        $this->assign('weappInfo', $this->weappInfo);
        /*--end*/
    }

    /**
     * 插件使用指南
     */
    public function doc(){
        return $this->fetch('doc');
    }

    /**
     * 系统内置钩子show方法（没用到这个方法，建议删掉）
     * 用于在前台模板显示片段的html代码，比如：QQ客服、对联广告等
     *
     * @param  mixed  $params 传入的参数
     */
    public function show($params = null){
        $map = array();
        $count = $this->db->where($map)->count('id');// 查询满足要求的总记录数
        $pageObj = new Page($count, 5);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageObj->url="/?m=home&c=Lists&a=index&tid=20&p=%5BPAGE%5D";
        $list = $this->db->where($map)->order('id desc')->limit($pageObj->firstRow.','.$pageObj->listRows)->select();
        $pageStr = $pageObj->show(); // 分页显示输出
        $this->assign('list', $list); // 赋值数据集
        $this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pager', $pageObj); // 赋值分页对象
        $this->assign("is_mobile",isMobile());
        echo $this->fetch('show');
    }

    /**
     * 插件后台管理 - 列表
     */
    public function index()
    {
        $list = array();
        $keywords = input('keywords/s');

        $map = array();
        if (!empty($keywords)) {
            $map['code'] = array('LIKE', "%{$keywords}%");
        }
        $batch=$this->request->param('batch');
        if($batch){
            $map['batch']=array('LIKE', "%{$batch}%");;
        }
        $maf_date=$this->request->param('maf_date');
        if($maf_date){
            $map['maf_date']=strtotime($maf_date);;
        }

        $count = $this->db->where($map)->count('id');// 查询满足要求的总记录数
        $pageObj = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数
        $list = $this->db->where($map)->order('id desc')->limit($pageObj->firstRow.','.$pageObj->listRows)->select();
        $pageStr = $pageObj->show(); // 分页显示输出
        $this->assign('list', $list); // 赋值数据集
        $this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pager', $pageObj); // 赋值分页对象
        $this->assign('keywords', $keywords);
        $this->assign('batch', $batch);
        $this->assign('maf_date', $maf_date);

        return $this->fetch('index');
    }

    public function test(){
        echo $this->general_cert();
    }

    public function general_cert($data,$id){
        $img_name=$id.'.png';
        $before_img_name = basename($data['certificate_img']);
        if($data['certificate_img'] && $img_name!=$before_img_name){
            //说明为手动上传了合格证，则不需要系统自动生成了
            return true;
        }
        $dst_path = WEAPP_PATH.'AirBottle'.DS.'template'.DS.'skin'.DS.'cert_muban.png';
        $fontsize=7;
        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        //打上文字
        $font = WEAPP_PATH.'AirBottle'.DS.'template'.DS.'skin'.DS.'fonts'.DS.'song.ttf';//字体路径
        $color = self::hex2rgb("#FF0000");
        $black = imagecolorallocate($dst, $color['r'], $color['g'], $color['b']);//字体颜色
        $date='2025-11-08';
        $xh_arr=explode('-',$data['xinghao']);
        $fields=[
            0=>['v'=>$data['xinghao'], 'x'=>180, 'y'=>178],
            1=>['v'=>$data['code'], 'x'=>180, 'y'=>210],
            2=>['v'=>date("Y 年 m 月",$data['maf_date']), 'x'=>180, 'y'=>240],
            3=>['v'=>date("Y年m月d日",$data['maf_date']), 'x'=>270, 'y'=>415],
            4=>['v'=>$data['capacity'], 'x'=>560, 'y'=>100],
            5=>['v'=>(isset($xh_arr[1])?$xh_arr[1]:''), 'x'=>560, 'y'=>120],
            6=>['v'=>($data['type']==154?$data['zd_czl']:$data['gfzd_czl']), 'x'=>570, 'y'=>160],
            7=>['v'=>($data['type']==154?$data['pt_hd']:$data['bihou']), 'x'=>575, 'y'=>183],
        ];
        foreach($fields as $k=>$v){
            imagefttext($dst, $fontsize*1.55, 0,  $v['x'], $v['y'], $black, $font, $v['v']);
        }


        $filepath = ROOT_DIR."uploads".DS.'cert'.DS.date("Ym").DS;
        $file_url="/uploads/cert/".date("Ym").'/'.$img_name;
        $filename = $filepath.$img_name;
        if(!file_exists($filepath)){
            @mkdir($filepath,0775,true);
        }
        imagepng($dst,$filename);
        imagedestroy($dst);
        $this->model->where(['id'=>$id])->update(['certificate_img'=>$file_url]);
        return $filename;

    }
    function hex2rgb($hexColor){
        $color=str_replace('#','',$hexColor);
        if (strlen($color)> 3){
            $rgb=array(
                'r'=>hexdec(substr($color,0,2)),
                'g'=>hexdec(substr($color,2,2)),
                'b'=>hexdec(substr($color,4,2))
            );
        }else{
            $r=substr($color,0,1). substr($color,0,1);
            $g=substr($color,1,1). substr($color,1,1);
            $b=substr($color,2,1). substr($color,2,1);
            $rgb=array(
                'r'=>hexdec($r),
                'g'=>hexdec($g),
                'b'=>hexdec($b)
            );
        }
        return $rgb;
    }

    public function qr(){
        $id=$this->request->param('id');
        $row=$this->db->where(['id'=>$id])->find();
        if($row['qr_code']){
            $this->assign('qr_url',$row['qr_code']);
        }else{
            $url=$this->getUrl($id);
            $this->getImg($url,$row['code'],$row['batch']);
            $qr_code='/uploads/qrcode/'.date('Ym').'/'.$row['batch'].'/'.$row['code'].'.png';
            $this->model->where(['id'=>$id])->update(['qr_code'=>$qr_code]);
            $this->assign('qr_url',$qr_code);
        }
        return $this->fetch();
    }

    public function getImg($code,$number,$batch){
        require_once ROOT_PATH."weapp".DS."AirBottle".DS."model".DS."phpqrcode.php"; //加载第三方库
        //$code=input('code');  //接受参数
        if(!$code)
            return ["code"=>404,"data"=>"传参数去!!!"];
        $errorCorrectionLevel = 'H';  //容错级别
        $matrixPointSize = 5;      //生成图片大小
        $file_path=ROOT_PATH.'uploads'.DS.'qrcode'.DS.date('Ym').DS.$batch;
        if(!is_dir($file_path)){
            // 创建文件夹
            @mkdir($file_path,0775,true);
        }
        //设置二维码文件名
        $file_name=$number.'.png';
        $filename = $file_path.DS.$file_name;
        if(file_exists($filename)){
            return ["code"=>200,"data"=>$filename];
        }
        $QRcode = new \QRcode();
        ob_start();
        $QRcode->png($code, false, $errorCorrectionLevel, $matrixPointSize, 1);
        $ob_contents = ob_get_contents(); //读取缓存区数据
        ob_end_clean();
        $myImage = ImageCreate(245,270); //参数为宽度和高度
        $qr = imagecreatefromstring($ob_contents);
        $qr_size = imagesx($qr);
        $img_x_y = (245-$qr_size)/2; //245为宽度
        $white = ImageColorAllocate($myImage, 255, 255, 255);
        $green=  ImageColorAllocate($myImage, 0, 0, 0);
        $font_path = WEAPP_PATH.'AirBottle'.DS.'template'.DS.'skin'.DS.'fonts'.DS.'simsun.ttc'; //引入字体
        imagettftext($myImage, 18, 0, 50, 255, $green, $font_path, $number);
        imagecopyresampled($myImage, $qr, $img_x_y, $img_x_y, 0, 0, $qr_size, $qr_size, $qr_size, $qr_size); //重新组合图片并调整大小
        //Header("Content-type: image/png");
        imagepng($myImage , $filename); //带文字二维码的文件名
        return   ["code"=>200,"data"=>$filename];
    }
    public function getUrl($id){
        $r=model('Config')->where(['name'=>'seo_pseudo'])->order('id desc')->find();
        if($r['value']==3){
            $url=$this->request->domain().'/plugins/air_bottle?id='.$id;
        }else{
            $url=$this->request->domain().'/index.php/plugins/air_bottle?id='.$id;
        }
        return $url;
    }
    /**
     * 插件后台管理 - 新增
     */
    public function add()
    {
        if (IS_POST) {
            $post = $this->request->post("row/a");
            $post['maf_date']=strtotime($post['maf_date']);
            /*组装存储数据*/
            $nowData = array(
                'add_time'    => getTime(),
                'update_time'    => getTime(),
                'batch'=>date('Ymd').'1001',
            );
            $saveData = array_merge($post, $nowData);
            /*--end*/
            $insertId = $this->db->insert($saveData);
            if (false !== $insertId) {
                $this->general_cert($saveData,$this->db->getLastInsID());
                adminLog('新增'.$this->weappInfo['name'].'：'.$post['code']); // 写入操作日志
                $this->success("操作成功", weapp_url('AirBottle/AirBottle/index'));
            }else{
                $this->error("操作失败");
            }
            exit;
        }

        return $this->fetch('add');
    }
    
    /**
     * 插件后台管理 - 编辑
     */
    public function edit()
    {
        if (IS_POST) {
            $post = $this->request->post('row/a');
            $post['maf_date']=strtotime($post['maf_date']);
            $post['id'] = eyIntval($this->request->post('id'));
            if(!empty($post['id'])){
                /*组装存储数据*/
                $nowData = array(
                    'update_time'    => getTime(),
                );
                $saveData = array_merge($post, $nowData);
                /*--end*/

                $r = $this->db->where(array('id'=>$post['id']))->update($saveData);
                if ($r) {
                    $this->general_cert($saveData,$post['id']);
                    adminLog('编辑'.$this->weappInfo['name'].'：'.$post['code']); // 写入操作日志
                    $this->success("操作成功!", weapp_url('AirBottle/AirBottle/index'));
                }
            }
            $this->error("操作失败!");
        }

        $id = input('id/d', 0);
        $row = $this->db->find($id);
        if (empty($row)) {
            $this->error('数据不存在，请联系管理员！');
            exit;
        }

        $this->assign('row',$row);

        return $this->fetch('edit');
    }
    
    /**
     * 删除文档
     */
    public function del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if(!empty($id_arr) && IS_POST){
            $result = $this->db->where("id",'IN',$id_arr)->select();
            $title_list = get_arr_column($result, 'title');

            $r = $this->db->where("id",'IN',$id_arr)->delete();
            if($r !== false){
                adminLog('删除'.$this->weappInfo['name'].'：'.implode(',', $title_list));
                $this->success("操作成功!");
            }
        }
        $this->error("操作失败!");
    }
    
    /**
     * 插件配置
     */
    public function conf()
    {
        if (IS_POST) {
            $post = $this->request->post('row/a');
            $post_img=$this->request->post('proimg/a');
            $post_img_txt=$this->request->post('imgintro/a');
            if($this->request->post('code')){
                $data = array(
                    'tag_weapp' => $post['tag_weapp'],
                    'update_time' => getTime(),
                );
                $banner=[];
                foreach ($post_img as $k=>$r){
                    if($r){
                        $banner[]=[
                            'image'=>$r,
                            'txt'=>(isset($post_img_txt[$k])?$post_img_txt[$k]:'')
                        ];
                    }
                }
                $post['banner']=$banner;
                //exit(var_dump($post));
                $data['data']=json_encode($post);
                $r = M('weapp')->where('code','eq',$this->request->post('code'))->update($data);
                if ($r) {
                    \think\Cache::clear('hooks');
                    adminLog('编辑'.$this->weappInfo['name'].'：插件配置'); // 写入操作日志
                    $this->success("操作成功!", weapp_url('AirBottle/AirBottle/conf'));
                }
            }
            $this->error("操作失败!");
        }

        $row = M('weapp')->where('code','eq','AirBottle')->find();
        $data=json_decode($row['data'],true);
        $this->assign('data', $data);
        $this->assign('row', $row);

        return $this->fetch('conf');
    }

    public function factory(){
        $factory_model=new AirFactoryModel();
        $row=$factory_model->where(['id'=>1])->find();
        if($this->request->isPost()){
            $post=$this->request->post('row/a');
            $factory_model->where(['id'=>1])->update($post);
            $this->success("更新成功");
        }
        $this->assign('row', $row);
        return $this->fetch('factory');
    }
    public function detail(){
        $id=$this->request->param('id');
        $row = $this->db->find($id);
        if (empty($row)) {
            $this->error('数据不存在，请联系管理员！');
            exit;
        }

        $this->assign('row',$row);

        return $this->fetch();
    }
    public function copy(){
        $id=$this->request->param('copy_id');
        $row = $this->db->find($id);
        if (empty($row)) {
            $this->error('数据不存在，请联系管理员！');
            exit;
        }
        unset($row['id']);
        $row['code']=$row['code'].' 复制';
        $insertId = $this->db->insert($row);
        if (false !== $insertId) {
            adminLog('复制'.$this->weappInfo['name'].'：'.$row['code']); // 写入操作日志
            $this->success("操作成功", weapp_url('AirBottle/AirBottle/index'));
        }else{
            $this->error("操作失败");
        }
        exit;

    }

    public function makeCert(){
        $batch=$this->request->param("batch");
        $list=$this->model->where(['batch'=>$batch,'certificate_img'=>''])->limit(50)->select();
        if(!$list){
            $this->success ( '生成结束！',weapp_url('AirBottle/AirBottle/index'));
        }
        foreach ($list as $k=>$r){
            $this->general_cert($r,$r['id']);
        }
        $this->success ( '合格证图片生成中...',weapp_url('AirBottle/AirBottle/makeCert','batch='.$batch));
    }
    public function import()
    {
        if($this->request->isPost()){
            $tmp_file = $_FILES ['file_stu'] ['tmp_name'];
            $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
            $file_type = $file_types [count ( $file_types ) - 1];

            /*判别是不是.xls文件，判别是不是excel文件*/
            if (strtolower ( $file_type ) != "xlsx" && strtolower ( $file_type ) != "xls")
            {
                $this->error ( '不是Excel文件，重新上传' );
            }
            /*设置上传路径*/
            $savePath = UPLOAD_PATH;
            /*以时间来命名上传的文件*/
            $str = date ( 'Ymdhis' );
            $file_name = $str . "." . $file_type;
            /*是否上传成功*/
            if (! copy ( $tmp_file, $savePath . $file_name ))
            {
                $this->error ( '上传失败' );
            }
            $res=$this->read(UPLOAD_PATH.$file_name,"UTF-8",$file_type);//传参,判断office2007还是office2003
            $fields=$this->titleToKey($res[1]);
            $data=[];
            $batch=date('Ymd').rand(1002, 9999);
            foreach ( $res as $k => $v ) //循环excel表
            {
                if($k==1) continue;
                $vv = array_combine($fields, $v);
                $vv['add_time']=time();
                $vv['update_time']=time();
                $vv['maf_date']=$this->get_date_by_excel($vv['maf_date']);
                $vv['batch']=$batch;
                $data[]=$vv;
            }
            $this->model->insertAll($data);
            //$this->writeLog(var_export($data,true));
            if(! $data)
            {
                $this->error('导入数据库失败');
            }
            else
            {
                $this->success ( '导入成功,生成合格证图片...',weapp_url('AirBottle/AirBottle/makeCert','batch='.$batch));
            }
        }else{
            return $this->fetch();
        }

    }
    protected function titleToKey($title){
        if(in_array('最大充装量',$title)){//有最大填充量的模板就是154类型
            $array=[
                '产品标题'=>'title',
                '型号类型'=>'type',
                '产品型号'=>'xinghao',
                '钢瓶编号'=>'code',
                '制造生产许可证'=>'licence',
                '生产日期'=>'maf_date',
                '充装介质'=>'dielectric',

                '最大充装量'=>'zd_czl',

                '钢瓶总重量'=>'weight',
                '瓶体材料'=>'cailiao',
                '公称容积'=>'capacity',


                '瓶体设计厚度'=>'pt_hd',
                '水压试验压力Pa'=>'sy',
                '气密性试验压力Pa'=>'qy',
                '热处理方式'=>'rcl',
                '公称工作压力MPa'=>'pressure',
                '瓶口螺纹'=>'luowen',
                '排序'=>'sort_order',
                '阀门厂家'=>'fm_factory',
                '阀门证书图'=>'fm_cert',
                '合格证图'=>'certificate_img',
                '质量证明书图'=>'quality_cert_img',
                '监督检验证书图'=>'testing_cert_img',
                '型式试验证书图'=>'ce_cert_img',
                '钢瓶编码图'=>'code_img',
            ];
        }else{
            $array=[
                '产品标题'=>'title',
                '型号类型'=>'type',
                '产品型号'=>'xinghao',
                '钢瓶编号'=>'code',
                '制造生产许可证'=>'licence',
                '生产日期'=>'maf_date',
                '充装介质'=>'dielectric',

                '干粉最大充装量'=>'gfzd_czl',
                '超细干粉最大充装量'=>'cx_czl',

                '钢瓶总重量'=>'weight',
                '瓶体材料'=>'cailiao',
                '公称容积'=>'capacity',


                '名义壁厚'=>'bihou',
                '钢瓶内径'=>'neijing',
                '工作温度'=>'wendu',

                '公称工作压力MPa'=>'pressure',
                '设计压力MPa'=>'sjyl',
                '排序'=>'sort_order',
                '合格证图'=>'certificate_img',
                '质量证明书图'=>'quality_cert_img',
                '监督检验证书图'=>'testing_cert_img',
                '型式试验证书图'=>'ce_cert_img',
                '钢瓶编码图'=>'code_img',
            ];
        }

        $data=[];
        foreach ($title as $k=>$v){
            if(isset($array[$v])){
                $data[$k]=$array[$v];
            }else{
                $data[$k]=$v;
            }
        }
        return $data;

    }
    public function get_date_by_excel($date){
        if (!$date || $date == '0000-00-00'){
            return time();
        }
        $unix_time = \PHPExcel_Shared_Date::ExcelToPHP($date);
        $add_time=gmdate('Y-m-d H:i:s',$unix_time);
        if($add_time){
            $add_time=strtotime($add_time);
        }else{
            $add_time=time();
        }
        return $add_time;

    }
    protected function writeLog($log)
    {
        $fp = fopen(RUNTIME_PATH. 'log/' . date('Y') . date('m') . date('d') . ".log.php", "a+");
        flock($fp, LOCK_EX);
        fwrite($fp, "<?php exit();?>RUN TIME:" . date('Y-m-d H:i:s') . "\n" . $log . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
    public function read($filename,$encode,$file_type){
        $path='PHPExcel-1-8.Classes.PHPExcel';
        weapp_vendor($path, 'AirBottle');
        weapp_vendor($path.".IOFactory",'AirBottle');

        if(strtolower ( $file_type )=='xls')//判断excel表类型为2003还是2007
        {
            weapp_vendor($path.".Reader.Excel5",'FwCode');
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }elseif(strtolower ( $file_type )=='xlsx')
        {
            weapp_vendor($path.".Reader.Excel2007",'FwCode');
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }
        }
        return $excelData;
    }

    public function setQrImg(){
        $where=[];
        $batch=$this->request->param('batch');
        if($batch){
            $where['batch']=array('LIKE', "%{$batch}%");
        }
        $keywords=$this->request->param('kw');
        if($keywords){
            $where['number']=array('LIKE', "%{$keywords}%");
        }
        $maf_date=$this->request->param('maf_date');
        if($maf_date){
            $where['maf_date']=strtotime($maf_date);
        }

        $list=$this->model->where($where)->where('qr_code',null)->order('id asc')->limit(500)->select();
        if(!$list){
            //$this->success("图片更新完毕，请重新导出图片",weapp_url('Trace/Trace/index'));
            $this->success("导出压缩包",weapp_url('AirBottle/AirBottle/importImgNew','batch='.$batch.'&kw='.$keywords.'&maf_date='.$maf_date));
        }
        $batch_no=time();
        foreach ($list as $k=>$r){
            $url=$this->getUrl($r['id']);
            $this->getImg($url,$r['code'],$batch?$batch:$batch_no);
            $this->model->where(['id'=>$r['id']])
                ->update(['qr_code'=>'/uploads/qrcode/'.date('Ym').'/'.($batch?$batch:$batch_no).'/'.$r['code'].'.png']);

        }
        $this->success("生成图片中[".$list[0]['id']."]...",weapp_url('AirBottle/AirBottle/setQrImg','batch='.$batch.'&kw='.$keywords.'&maf_date='.$maf_date));

    }
    public function importImgNew(){
        $where=[];
        $keywords=$this->request->param('kw');
        $batch=$this->request->param('batch');
        $maf_date=$this->request->param('maf_date');
        if($batch){
            $where['batch']=array('LIKE', "%{$batch}%");
        }
        if($keywords){
            $where['code']=array('LIKE', "%{$keywords}%");
        }
        if($maf_date){
            $where['maf_date']=strtotime($maf_date);
        }
        $count=$this->model->where($where)->where('qr_code',null)->count();
        if($count){
            $this->success("生成图片中...",weapp_url('AirBottle/AirBottle/setQrImg','batch='.$batch.'&kw='.$keywords.'&maf_date='.$maf_date));
        }
        $list=$this->model->where($where)->limit(50000)->select();
        if(!$batch){
            $batch=time();
        }
        $file_path=ROOT_PATH.'uploads'.DS.'qrcode'.DS.date('Ym').DS."zip".$batch;
        if(!is_dir($file_path)){
            // 创建文件夹
            @mkdir($file_path,0775,true);
        }
        $zip_name=$batch.'.zip';

        $files=[];
        foreach ($list as $k=>$r){
            $files[]=ROOT_PATH.$r['qr_code'];
        }

        $this->zip($files,$zip_name,$file_path);
        $zip_url=$this->request->domain().'/uploads/qrcode/'.date('Ym').'/zip'.$batch.'/'.$zip_name;
        $this->success("压缩完毕！!",$zip_url);


    }

    public function doZip(){
        $batch=$this->request->param('batch');
        $file_path=ROOT_PATH.'uploads'.DS.'qrcode'.DS.date('Ym').DS.$batch;
        $zip_name=$batch.'.zip';
        $this->zip($this->getFiles($file_path),$zip_name,$file_path);
        $zip_url=$this->request->domain().'/uploads/qrcode/'.date('Ym').'/'.$batch.'/'.$zip_name;
        $this->success("压缩完毕！",$zip_url);
    }

    public function zip($files, $filename,$path)
    {
        $zip = new \ZipArchive;

        $res = $zip->open($path . DS . $filename, \ZipArchive::CREATE);

        if ($res == true) {
            foreach ($files as $file) {
                $ff=explode('/',$file);
                $num=count($ff)-1;//获取文件名
                if ($t = $zip->addFile( $file,isset($ff[$num])?$ff[$num]:time().'.png' )  ) {
                    $t = $zip->addFile( $file, isset($ff[$num])?$ff[$num]:time().'.png'   );
                }
            }
            $zip->close();
            return true;
        } else {
            return false;
        }
    }
    public function getFiles($path, &$files = array(), $preg = "/\.(gif|jpeg|jpg|png|bmp|webp)$/i")
    {
        if (!is_dir($path))
            return null;
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path .'/' . $file; //'/' .

                //   dump($path2);

                if (is_dir($path2)) {
                    self::getFiles($path2, $files);
                } else {
                    if (preg_match($preg, $file)) {
                        $files [] = $path2;
                    }
                }
            }
        }
        return $files;
    }
}